﻿using System;
using ch02.binary.module;

namespace ch02.binary.wasm_reader
{
    public partial struct WasmReader
    {
        // code sec
        private Code[] ReadCodeSec()
        {
            var vec = new Code[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = ReadCode();
            }

            return vec;
        }

        private Code ReadCode()
        {
            var codeReader = new WasmReader() {Data = ReadBytes()};
            var code = new Code
            {
                Locals = codeReader.readLocalsVec(),
                //Expr:   reader.readExpr(),
            };
            if (code.GetLocalCount() >= UInt32.MaxValue)
            {
                Panic.Run("too many locals: %d",
                    code.GetLocalCount());
            }

            return code;
        }

        Locals[] readLocalsVec()
        {
            var vec = new Locals[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = readLocals();
            }

            return vec;
        }

        Locals readLocals()
        {
            return new Locals
            {
                N = ReadVarU32(),
                Type = ReadValType(),
            };
        }
    }
}